package com.sltx.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sltx.controller.base.BaseController;
import com.sltx.mapper.LogMapper;
import com.sltx.util.PageData;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/tianyancha")
@ResponseBody
public class TianyanchaController extends BaseController {

    @Value("${token-key}")
    private String token_key;

    @Autowired
    private LogMapper logMapper;

    //
    @RequestMapping("/normal")
    public Object taxpayer(HttpServletRequest request) {
        PageData pd = this.getPageData();
        JSONObject jsonObject = null;
        JSONObject jsonObject1 = null;
        String token = token_key;
        //查询所有企业股东
        List<String> qygs = logMapper.getqygd(pd);
        for (String qyg : qygs) {
            pd.put("entName", qyg);
            String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?";
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
            HttpConnectionParams.setSoTimeout(httpParams, 1000);
            HttpClient httpClient = new DefaultHttpClient(httpParams);
            String result = null;
            try {
                HttpGet get = new HttpGet(url + "keyword=" + qyg);
                // 设置header
                get.setHeader("Authorization", token);
                // 设置类型
                HttpResponse response = httpClient.execute(get);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            jsonObject = JSONObject.fromObject(result);
            if (jsonObject.get("result").equals(null)) {
                System.out.println(qyg);
            } else {
                Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");
                if (result1.get("id").equals(null)) {
                    System.out.println(qyg);
                } else {
                    String id = result1.get("id").toString();
                    //根据id调用获取标签接口
                    String url1 = "http://open.api.tianyancha.com/services/open/cd/tags/2.0?";
                    String result3 = null;
                    try {
                        HttpGet get1 = new HttpGet(url1 + "id=" + id);
                        // 设置header
                        get1.setHeader("Authorization", token);
                        // 设置类型
                        HttpResponse response1 = httpClient.execute(get1);
                        HttpEntity entity1 = response1.getEntity();
                        result3 = EntityUtils.toString(entity1, "utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        httpClient.getConnectionManager().shutdown();
                    }
                    jsonObject1 = JSONObject.fromObject(result3);
                    if (jsonObject1.get("result").equals(null)) {
                        pd.put("code", "0");
                        logMapper.updatecode(pd);
                    } else {
                        Map<String, Object> result2 = (Map<String, Object>) jsonObject1.get("result");
                        List<String> items = (List<String>) result2.get("items");
                        for (String item : items) {
                            //如果item为私募基金状态就为1
                            if (item.equals("私募基金")) {
                                pd.put("code", "1");
                                logMapper.updatecode(pd);
                            } else {
                                pd.put("code", "0");
                                logMapper.updatecode(pd);
                            }
                        }
                    }

                }
            }


        }
        return "ok";
    }

    //基本信息接口-测试
    @RequestMapping("/jbxx")
    @ResponseBody
    public Object normal(HttpServletRequest request) throws InterruptedException {

        PageData pd = this.getPageData();
        //查询所有企业股东
        List<String> qygs = logMapper.getqygd(pd);
        for (String qyg : qygs) {
            pd.put("entName", qyg);
            JSONObject jsonObject = null;
            String token = token_key;
            String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?";
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
            HttpConnectionParams.setSoTimeout(httpParams, 1000);
            HttpClient httpClient = new DefaultHttpClient(httpParams);
            String result = null;
            try {
                HttpGet get = new HttpGet(url + "keyword=" + qyg);
                // 设置header
                get.setHeader("Authorization", token);
                // 设置类型
                HttpResponse response = httpClient.execute(get);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
            jsonObject = JSONObject.fromObject(result);

            if (jsonObject.get("result").equals(null)) {
                pd.put("code", "2");
                logMapper.updatecode(pd);
                Thread.sleep(10000l);
            } else {
                Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");
                String[] split = result1.get("tags").toString().split(";");
                boolean containsPrivateFund = contains(split, "私募基金");
                if (containsPrivateFund) {
                    pd.put("code", "1");
                    logMapper.updatecode(pd);
                    Thread.sleep(10000l);
                } else {
                    pd.put("code", "2");
                    logMapper.updatecode(pd);
                    Thread.sleep(10000l);
                }
            }
        }
        return "ok";

    }

    public static boolean contains(String[] arr, String target) {
        for (String fund : arr) {
            // 这里使用contains方法检查当前基金名称是否包含目标字符串
            if (fund.contains(target)) {
                return true; // 找到匹配项，返回true
            }
        }
        return false; // 遍历完数组后未找到匹配项，返回false
    }

    //基本信息接口
    @RequestMapping("/getnormal")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ResponseBody
    public Object getnormal(HttpServletRequest request) throws InterruptedException {

        PageData pd = this.getPageData();
        //查询所有企业股东
        String entName = pd.getString("entName");
        JSONObject jsonObject = null;
        String token = token_key;
        String url = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal?";
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url + "keyword=" + entName);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        String s = Optional.ofNullable(result).orElse("");
        jsonObject =  JSONObject.fromObject(s);

        return jsonObject;

    }


    //私募基金接口
    @RequestMapping("/privateFund")
    public Object privateFund(HttpServletRequest request) {
        PageData pd = this.getPageData();
        JSONObject jsonObject = null;
        String token = token_key;
        String url = "http://open.api.tianyancha.com/services/open/cd/privateFund/2.0?";
        String entName = pd.get("entName").toString();
        String pageSize = pd.get("pageSize").toString();
        String pageNum = pd.get("pageNo").toString();
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url + "keyword=" + entName + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        jsonObject = JSONObject.fromObject(result);
        if (jsonObject.get("result").equals(null)) {
            jsonObject.put("result", "");
            return jsonObject;
        }
        Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");

        return result1;
    }

    //获取标签
    @RequestMapping("/tags")
    public Object tags(HttpServletRequest request) {
        PageData pd = this.getPageData();
        JSONObject jsonObject = null;
        String token = token_key;
        String url = "http://open.api.tianyancha.com/services/open/cd/tags/2.0?";
        String id = pd.get("id").toString();
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url + "id=" + id);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        jsonObject = JSONObject.fromObject(result);
        if (jsonObject.get("result").equals(null)) {
            jsonObject.put("result", "");
            return jsonObject;
        }
        Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");

        return result1;
    }

    //搜索接口
    @RequestMapping("/search")
    public Object search(HttpServletRequest request) {
        PageData pd = this.getPageData();
        JSONObject jsonObject = null;
        String token = token_key;
        String url = "http://open.api.tianyancha.com/services/open/search/2.0?";
        String entName = pd.get("entName").toString();
        String pageSize = pd.get("pageSize").toString();
        String pageNum = pd.get("pageNo").toString();
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url + "word=" + entName + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        jsonObject = JSONObject.fromObject(result);
        if (jsonObject.get("result").equals(null)) {
            jsonObject.put("result", "");
            return jsonObject;
        }
        Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");

        return result1;
    }

    //投资机构
    @RequestMapping("/investOrg")
    public Object investOrg(HttpServletRequest request) {
        PageData pd = this.getPageData();
        JSONObject jsonObject = null;
        String token = token_key;
        String url = "http://open.api.tianyancha.com/services/open/cd/investOrg/2.0?";
        String entName = pd.get("entName").toString();
        String pageSize = pd.get("pageSize").toString();
        String pageNum = pd.get("pageNo").toString();
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url + "keyword=" + entName + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        jsonObject = JSONObject.fromObject(result);
        if (jsonObject.get("result").equals(null)) {
            jsonObject.put("result", "");
            return jsonObject;
        }
        Map<String, Object> result1 = (Map<String, Object>) jsonObject.get("result");

        return result1;
    }
}

